{% include 'public/body.html' %}

{% block title %}

    资源上传
{% endblock %}


{% block main %}
    <!-- 网站主体 -->
    <div id="main">
        <section class="ct">
            <!-- 上传表单-->
            <div class="upload">
                <h1>
                    上传资源<em>声明：请确保您上传的内容合法合规，涉及侵权内容将会被移除，详见<a>《爱下载资源共享规则》</a></em>
                </h1>
                <form enctype="multipart/form-data">

                    <p class="file">
                        <input type="file" name="resource" @change="uploadFile">

                        <span class="t1" v-if="!isUpload">点击上传、文件小于1000MB（请不要上传存在侵权的资源哦！）</span>

                        <!-- 上传后的效果 -->
                        <span class="t2" v-else>
                            <img :src="file.dataUrl"/>
                            <b v-text="file.name"></b>
                            <progress :value="uploadProgress" max="100"></progress>
                            <a v-text="progress">重新上传</a>
                        </span>

                    </p>

                    <p>
                        <label><em>*</em>资源名称：</label>
                        <input class="upt" type="text" name="resourceName" v-model="formData.resourceName"
                               placeholder="请输入资源名"/>
                        <em></em> <!-- 显示错误信息  -->
                    </p>

                    <p>
                        <label>资源描述：</label>
                        <textarea class="area" v-model="formData.description"
                                  placeholder="简要介绍一下资源内容"></textarea>
                    </p>

                    <p>
                        <label><em>*</em>关键词：</label>
                        <span class="key-tag">
                            <a class="key">

                                <span v-for="(tag, index) in formData.tags" :key="index"
                                      @click.prevent.stop="removeTag(index)" class="tag-item" v-text="tag">

                                </span>

                                <!-- 单击添加标签后、产生的效果 -->
                                <input type="text" v-show="isAddTag" @keydown.enter="addTag" v-model="newTags"
                                       @blur="newTags=''"/>
                            </a>

                            <span class="key-tag-msg">
                                <button type="button" class="keywords add" @click="isAddTag=true"
                                        v-model="newTags">添加标签</button>
                                <i class="lb">按回车键创建标签</i>
                            </span>
                        </span>

                        <span class="source-tag-msg">最多添加5个标签，每个标签不超过16个字</span>
                    </p>


                    <div class="source-type-div">
                        <p>
                            <label>所属分类：</label>
                            <select class="upt source-type source-type-down" v-model="formData.category">
                                name="category">

                                {% for parent in catalog_tree %}
                                    <optgroup label="{{ parent.catalog.name }}">
                                        {% for child in parent.children %}
                                            <option value="{{ child.pk }}">{{ child.name }}</option>

                                        {% endfor %}
                                    </optgroup>
                                {% endfor %}

                            </select>
                        </p>
                    </div>

                    <p>
                        <label><em>*</em>资源分：</label>
                        <select class="upt" id="sel" name="score" v-model="formData.score">
                            <option selected="selected">0</option>
                            <option>1</option>
                            <option>2</option>
                            <option>3</option>
                            <option>4</option>
                            <option>5</option>
                        </select>
                    </p>

                    <p>
                        <label>验证码：</label>
                        <input id="code" class="upt captcha" type="text" name="code" v-model="formData.captcha"
                               value="" placeholder="请输入验证码,如果看不清，点击验证码进行刷新"/>
                        <img class="captcha" src="{% url 'res:captcha' %}?w=140&h=40"
                             alt="验证码" @click="changeCaptcha" ref="captchaImg"/>
                        <em></em>
                    </p>

                    <p @click="sub"><label class="btn"><a class="btn">提交</a></label></p>
                </form>
            </div>
        </section>
    </div>

{% endblock %}

{% block vue %}
    <script>
        Vue.createApp({
            data() {
                return {
                    file: {
                        document: null, //用户文件
                        name: '', //文件名字
                        size: 0,//文件大小
                        dataUrl: '', //文件的 dataUrl
                        type: 'zip'
                    },
                    isUpload: false, //是否显示文件上传后的效果
                    uploadProgress: 0, //上传进度
                    progress: '',//进度显示百分比
                    newTags: "", //新添加的标签

                    isAddTag: false, //是否显示添加标签的输入框

                    formData: {
                        resourceName: '',
                        description: '',
                        tags: ["python", "vue"],
                        category: '',
                        score: '0',
                        captcha: ''
                    }
                }
            },
            methods: {
                changeCaptcha(event) {
                    //刷新 验证码
                    const captchaImg = this.$refs.captchaImg;
                    captchaImg.src = "{% url 'res:captcha' %}?w=140&h=40&" + Math.random();
                },
                uploadFile(event) {

                    //获取上传的文件对象 （File)
                    const file = event.target.files[0];
                    this.file.document = file;
                    this.file.name = file.name;
                    this.file.size = file.size;
                    this.file.type = file.name.split('.').pop().toLowerCase();

                    //资源类型图标显示
                    this.file.dataUrl = '/static/images/' + this.file.type + '.svg';

                    this.isUpload = true

                    //文件上传
                    const formData = new FormData()
                    formData.append('document', this.file.document);
                    formData.append('ext', this.file.type);
                    formData.append('size', this.file.size);

                    axios.post('{% url "res:upload_file" %}', formData, {
                        onUploadProgress: (progressEvent) => {

                            if (progressEvent.event.lengthComputable) {
                                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                                console.log(`上传进度: ${percentCompleted}%`);
                                // 更新进度条
                                this.uploadProgress = percentCompleted;
                                this.progress = `${percentCompleted}%`;
                            }
                        }

                    }).then(res => {
                        if (res.data.code === 200) {
                            this.progress = '重新上传'
                            layer.msg('文件上传成功', {icon: 1});
                        }

                    }).catch(error => {
                        layer.msg('文件上传失败，请重试', {icon: 2});
                    });
                },

                addTag() {
                    this.isAddTag = true

                    if (this.formData.tags.length >= 5) {
                        layer.msg('最多添加5个标签', {icon: 2});
                        this.newTags = "";
                        return;
                    }
                    if (this.newTags.length > 16) {
                        layer.msg('每个标签不超过16个字', {icon: 2});
                        this.newTags = "";
                        return;
                    }
                    if (this.newTags.trim() === "") {
                        layer.msg('标签不能为空', {icon: 2});
                        this.newTags = "";
                        return;
                    }
                    //检查标签是否重复
                    if (this.formData.tags.includes(this.newTags.trim())) {
                        layer.msg('标签已存在', {icon: 2});
                        this.newTags = "";
                        return;
                    }
                    this.formData.tags.push(this.newTags.trim());
                    this.newTags = "";
                },
                removeTag(index) {
                    //删除 标签
                    this.formData.tags.splice(index, 1);
                },
                sub() {

                    if (!this.isUpload) {
                        layer.msg('请上传资源文件', {icon: 2});
                        return;
                    }
                    if (this.formData.resourceName.trim() === '') {
                        layer.msg('资源名称不能为空', {icon: 2});
                        return;
                    }
                    if (!this.formData.tags) {
                        layer.msg('请添加关键词标签', {icon: 2});
                        return;
                    }
                    if (this.formData.captcha.trim() === '') {
                        layer.msg('请输入验证码', {icon: 2});
                        return;
                    }

                    //提交表单
                    const formData = new FormData();
                    formData.append('resourceName', this.formData.resourceName);
                    formData.append('description', this.formData.description);
                    formData.append('tags', this.formData.tags.join(','));
                    formData.append('category', this.formData.category);
                    formData.append('score', this.formData.score);
                    formData.append('captcha', this.formData.captcha);

                    axios.post('{% url "res:upload_res" %}', formData).then(res => {

                        if (res.data.code === 200) {
                            layer.msg('资源上传成功', {icon: 1}, function () {
                                // 跳转到 资源详情页
                                setTimeout(() => {
                                    window.location.href = `/res/detail/${res.data.res_id}/`;
                                }, 1000)
                            })

                        } else {
                            layer.msg(res.data.msg, {icon: 2})
                            this.changeCaptcha();

                        }

                    })
                }

            }
        }).mount('#main');

    </script>

{% endblock %}